<?php

class DbmDb extends CComponent {
	protected $_dbConnection = null;
	public $_dbName;
	protected $_tables = array();
	private static $_instance = null;
	protected $_packages = array();
	
	public function getPackages() {
		if(!$this->_packages) {
			foreach($this->getTables() as $table) {
				$package = $table->package;
				$this->_packages[$package][] = $table;
			}
		}
		return $this->_packages;
	}
	
	public function __construct() {
		$this->_dbConnection = Yii::app()->db;
	}
	
	public static function getInstance() {
		if(!self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	public function getTables($refresh = false) {
		if(!$this->_tables || $refresh) {
			$tables = DbmTableInfo::model()->findAll();
			$this->_tables = array();
			foreach($tables as $table) {
				$this->_tables[$table->table_name] = $table;
			}
		}
		return $this->_tables;
	}
	
	public function getDbName() {
		if(!$this->_dbName) {
			$connectionString = Yii::app()->db->connectionString;
			preg_match('/dbname=(.*)/i', $connectionString, $matches);
			$this->_dbName = $matches[1];
		}
		return $this->_dbName;
	}
	
	public function __get($name) {
		if(parent::__isset($name)) {
			return parent::__get($name);
		} elseif(isset($this->_dbConnection->$name)) {
			return $this->_dbConnection->$name;
		}
		return parent::__get($name);
	}
	
	public function __call($method, $params) {
		return call_user_func_array(array($this->_dbConnection, $method), $params);
	}
	
}

?>